from rest_framework import serializers
from .models import SystemBackup, BackupOperation


class SystemBackupSerializer(serializers.ModelSerializer):
    """系统备份序列化器"""
    
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)
    last_restored_by_name = serializers.CharField(source='last_restored_by.username', read_only=True)
    backup_type_display = serializers.CharField(source='get_backup_type_display', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    size_display = serializers.CharField(source='get_backup_size_display', read_only=True)
    
    class Meta:
        model = SystemBackup
        fields = [
            'id', 'backup_type', 'backup_type_display', 'status', 'status_display',
            'created_by', 'created_by_name', 'created_at', 'completed_at',
            'description', 'checksum', 'size_bytes', 'size_display', 'is_valid',
            'restore_count', 'last_restored_at', 'last_restored_by_name'
        ]
        read_only_fields = [
            'id', 'created_at', 'completed_at', 'checksum', 'size_bytes',
            'restore_count', 'last_restored_at', 'last_restored_by'
        ]

    def validate_description(self, value):
        """验证描述字段"""
        if len(value.strip()) == 0:
            raise serializers.ValidationError("备份描述不能为空")
        return value.strip()


class BackupCreateSerializer(serializers.Serializer):
    """创建备份序列化器"""
    
    backup_type = serializers.ChoiceField(
        choices=SystemBackup.BACKUP_TYPES,
        default='manual'
    )
    description = serializers.CharField(
        max_length=500,
        required=True,
        help_text="备份描述"
    )
    include_menu_data = serializers.BooleanField(default=True)
    include_permission_data = serializers.BooleanField(default=True)
    include_file_data = serializers.BooleanField(default=False)
    include_config_data = serializers.BooleanField(default=True)

    def validate_description(self, value):
        """验证描述"""
        if not value or len(value.strip()) == 0:
            raise serializers.ValidationError("备份描述不能为空")
        return value.strip()


class BackupRestoreSerializer(serializers.Serializer):
    """恢复备份序列化器"""
    
    backup_id = serializers.IntegerField(required=True)
    restore_menu_data = serializers.BooleanField(default=True)
    restore_permission_data = serializers.BooleanField(default=True)
    restore_file_data = serializers.BooleanField(default=False)
    restore_config_data = serializers.BooleanField(default=True)
    force_restore = serializers.BooleanField(default=False, help_text="强制恢复，忽略警告")

    def validate_backup_id(self, value):
        """验证备份ID"""
        try:
            backup = SystemBackup.objects.get(id=value, is_valid=True)
            if backup.status != 'completed':
                raise serializers.ValidationError("只能恢复已完成的备份")
            return value
        except SystemBackup.DoesNotExist:
            raise serializers.ValidationError("备份不存在或已损坏")


class BackupOperationSerializer(serializers.ModelSerializer):
    """备份操作序列化器"""
    
    operated_by_name = serializers.CharField(source='operated_by.username', read_only=True)
    operation_type_display = serializers.CharField(source='get_operation_type_display', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    backup_description = serializers.CharField(source='backup.description', read_only=True)
    
    class Meta:
        model = BackupOperation
        fields = [
            'id', 'backup', 'backup_description', 'operation_type', 'operation_type_display',
            'status', 'status_display', 'started_at', 'completed_at',
            'operated_by', 'operated_by_name', 'operation_data', 'result_data',
            'error_message', 'duration_seconds', 'processed_items'
        ]
        read_only_fields = [
            'id', 'started_at', 'completed_at', 'duration_seconds'
        ]


class BackupListSerializer(serializers.ModelSerializer):
    """备份列表序列化器（简化版）"""
    
    created_by_name = serializers.CharField(source='created_by.username', read_only=True)
    backup_type_display = serializers.CharField(source='get_backup_type_display', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    size_display = serializers.CharField(source='get_backup_size_display', read_only=True)
    
    class Meta:
        model = SystemBackup
        fields = [
            'id', 'backup_type', 'backup_type_display', 'status', 'status_display',
            'created_by_name', 'created_at', 'description', 'size_display',
            'is_valid', 'restore_count'
        ]


class BackupStatisticsSerializer(serializers.Serializer):
    """备份统计序列化器"""
    
    total_backups = serializers.IntegerField()
    valid_backups = serializers.IntegerField()
    total_size_bytes = serializers.IntegerField()
    total_size_display = serializers.CharField()
    recent_backups_count = serializers.IntegerField()
    last_backup_date = serializers.DateTimeField(allow_null=True)
    backup_types_breakdown = serializers.DictField()
    monthly_backup_count = serializers.DictField()


class RecoveryOptionsSerializer(serializers.Serializer):
    """恢复选项序列化器"""
    
    available_backups = BackupListSerializer(many=True)
    recommended_backup_id = serializers.IntegerField(allow_null=True)
    warnings = serializers.ListField(child=serializers.CharField())
    estimated_restore_time = serializers.CharField()
    affected_components = serializers.ListField(child=serializers.CharField())
